{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "from torchvision import datasets, transforms\n",
    "from torch.utils.data import DataLoader\n",
    "\n",
    "import cv2\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 打开数据集\n",
    "with open(\"./data/MNIST/raw/train-images-idx3-ubyte\", \"rb\") as f:\n",
    "    file = f.read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 提取前100张保存为图片\n",
    "for i in range(1, 100):\n",
    "    img1 = [int(str(item).encode('ascii'), 16) for item in file[16 + 784 * (i - 1) : 16 + 784 * i]]\n",
    "    # print(len(img1))\n",
    "    # 考虑识别精度问题须使用float进行保存\n",
    "    img1_np = np.array(img1, dtype=np.float32).reshape(28, 28, 1)\n",
    "    cv2.imwrite(f\"./pics/{i}.jpg\", img1_np)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
